<template>
  <el-form
    :model="ruleForm"
    :rules="rules"
    ref="ruleForm"
    label-width="100px"
    class="content"
  >
    <el-form-item :label='$t("Write.blogTitle")' prop="title">
      <el-input v-model="ruleForm.title"></el-input>
    </el-form-item>
    <el-form-item :label='$t("Write.blogType")' prop="region">
      <el-select v-model="ruleForm.region" :placeholder='$t("Write.selectBlogType")'>
        <el-option
          v-for="item in blog.blogTypeList"
          :key="item.Id"
          :label="item.TypeName"
          :value="item.Id"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item :label='$t("Write.uploadPicture")' prop="pic">
      <upload icon="el-icon-folder-add" v-model:url="ruleForm.url"> </upload>
    </el-form-item>
    <el-form-item :label='$t("Write.blogContent")' prop="desc">
      <el-input type="textarea" v-model="ruleForm.desc"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm('ruleForm')"
        >{{$t("Write.commit")}}</el-button
      >
      <el-button @click="resetForm('ruleForm')"
        >{{$t("Write.reset")}}</el-button
      >
    </el-form-item>
  </el-form>
</template>

<script>
import upload from "@/components/upload";
import { mapGetters } from "vuex";
export default {
  computed: {
    ...mapGetters(["user"]),
    ...mapGetters(["blog"]),
  },
  components: {
    upload,
  },
  data() {
    return {
      dialogImageUrl: "",
      ruleForm: {
        title: "",
        region: "",
        desc: "",
        url: "",
      },
      rules: {
        title: [
          { required: true, message: "请输入文章标题", trigger: "blur" },
          {
            min: 3,
            max: 15,
            message: "长度在 3 到 15 个字符",
            trigger: "blur",
          },
        ],
        region: [
          { required: true, message: "请选择文章类型", trigger: "change" },
        ],
        desc: [{ required: true, message: "请填写文章内容", trigger: "blur" }],
      },
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (!this.user.userEmail) {
            this.$message.error("请先登录");
            this.$router.push({ name: "Login" });
            return;
          }
          this.$api.blog
            .writeBlog({
              BlogTypeId: this.ruleForm.region,
              Title: this.ruleForm.title,
              Email: this.user.userEmail,
              Content: this.ruleForm.desc,
              Pic: this.ruleForm.url,
            })
            .then((data) => {
              this.$message.success(data.msg);
              this.$router.push({ path: "/blogType/"+this.ruleForm.region });
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>
<style>
</style>